<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body @close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="秒杀名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入秒杀名称" />
        </el-form-item>
        <el-form-item label="秒杀时间段" prop="startTime">
          <el-time-select
            v-model="formData.startTime"
            :picker-options="hourPickerOptions"
            placeholder="起始时间"
            @change="handleTimeChange('startTime')"
            style="width: 45%; margin-right: 10px;"
          />
          <el-time-select
            v-model="formData.endTime"
            :picker-options="hourPickerOptions"
            placeholder="结束时间"
            @change="handleTimeChange('endTime')"
            style="width: 45%;"
          />
        </el-form-item> 
        <el-form-item label="轮播图" prop="silderImgs">
          <div class="image-upload-container">
            <ImageUpload v-model="formData.silderImgs" @input="handleImageUpload" :limit="10" />
            <div v-if="formData.silderImgs && formData.silderImgs.length > 0" class="image-preview-container">
              <draggable 
                v-model="formData.silderImgs" 
                class="image-list"
                @end="handleDragEnd"
                :animation="150"
                ghost-class="ghost"
                handle=".drag-handle"
              >
                <div v-for="(url, index) in formData.silderImgs" :key="index" class="image-item">
                  <div class="drag-handle">
                    <i class="el-icon-rank"></i>
                  </div>
                  <el-image 
                    :src="url" 
                    fit="cover"
                    class="preview-image"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                  <div class="image-actions">
                    <el-button 
                      type="text" 
                      icon="el-icon-delete" 
                      @click="removeImage(index)"
                    ></el-button>
                  </div>
                </div>
              </draggable>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as StoreSeckillMangerApi from '@/api/marketing/storeseckillmanger';
import ImageUpload from '@/components/ImageUpload';
import draggable from 'vuedraggable';

export default {
  name: "StoreSeckillMangerForm",
  components: { 
    ImageUpload,
    draggable
  },
  data() {
    return {
      dialogTitle: "",
      dialogVisible: false,
      formLoading: false,
      formData: {
        id: null,
        name: null,
        startTime: null,
        endTime: null,
        silderImgs: [], // 只存储图片url数组
        status: "1", // 默认开启
      },
      formRules: {
        name: [{ required: true, message: '秒杀名称不能为空', trigger: 'blur' }],
        startTime: [{ required: true, message: '起始时间不能为空', trigger: 'change' }],
        endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
        silderImgs: [{ required: true, message: '轮播图不能为空', trigger: 'change' }],
      },
      tempStartTime: null,
      tempEndTime: null,
      hourPickerOptions: {
        start: '00:00',
        step: '01:00',
        end: '23:00',
        formatter(time) {
          if (!time) return '';
          const hour = time.getHours();
          return `${hour.toString().padStart(2, '0')}:00`;
        },
        parser(value) {
          if (!value) return null;
          const [hour] = value.split(':');
          const date = new Date();
          date.setHours(parseInt(hour, 10), 0, 0, 0);
          return date;
        },
      },
    };
  },
  computed: {
    startTimePickerOptions() {
      return {
        ...this.hourPickerOptions,
        disabledHours() {
          if (this.formData.endTime !== null) {
            return hour => hour >= this.formData.endTime;
          }
          return [];
        },
      };
    },
    endTimePickerOptions() {
      return {
        ...this.hourPickerOptions,
        disabledHours() {
          if (this.formData.startTime !== null) {
            return hour => hour <= this.formData.startTime;
          }
          return [];
        },
      };
    },
  },
  methods: {
    // 处理对话框关闭
    handleDialogClose() {
      this.reset();
      this.formData.silderImgs = [];
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },
    // 处理图片上传，转换为指定格式
    handleImageUpload(value) {
      if (!value) {
        this.formData.silderImgs = [];
        return;
      }
      if (Array.isArray(value)) {
        this.formData.silderImgs = value.map(item => {
          if (typeof item === 'string') return item;
          if (item.url) return item.url;
          if (item.response && item.response.url) return item.response.url;
          return '';
        }).filter(Boolean);
      } else if (typeof value === 'string') {
        this.formData.silderImgs = value.split(',').filter(url => url.trim());
      }
    },
    handleTimeChange(type) {
      const currentHour = this.formData[type];
      if (currentHour === null) return;

      if (type === 'startTime' && this.formData.endTime !== null) {
        if (currentHour >= this.formData.endTime) {
          this.$message.warning('开始时间不能晚于结束时间');
          this.formData[type] = this.tempStartTime;
          return;
        }
        this.tempStartTime = currentHour;
      } else if (type === 'endTime' && this.formData.startTime !== null) {
        if (currentHour <= this.formData.startTime) {
          this.$message.warning('结束时间不能早于开始时间');
          this.formData[type] = this.tempEndTime;
          return;
        }
        this.tempEndTime = currentHour;
      }
    },
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      
      if (id) {
        this.formLoading = true;
        try {
          const res = await StoreSeckillMangerApi.getStoreSeckillManger(id);
          // 先设置基本信息
          this.formData = {
            id: res.data.id,
            name: res.data.name,
            startTime: this.formatHour(res.data.startTime),
            endTime: this.formatHour(res.data.endTime),
            status: res.data.status ? "1" : "0",
            silderImgs: [] // 先设置为空数组
          };
          this.dialogTitle = "修改秒杀活动";
          
          // 等待下一个tick，确保表单已经渲染
          await this.$nextTick();
          // 再设置图片数据
          this.formData.silderImgs = this.parseImageData(res.data.silderImgs);
        } catch (error) {
          this.$message.error("获取数据失败: " + error.message);
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增秒杀活动";
      }
    },
    formatHour(hour) {
      return hour !== null ? `${hour.toString().padStart(2, '0')}:00` : '00:00';
    },
    timeToHour(timeStr) {
      if (!timeStr || typeof timeStr !== 'string') return null;
      return parseInt(timeStr.split(':')[0], 10);
    },
    async submitForm() {
      try {
        await this.$refs.formRef.validate();
        
        if (this.formData.startTime >= this.formData.endTime) {
          throw new Error('开始时间必须早于结束时间');
        }
        
        this.formLoading = true;

        // 提交时转换为后端需要的对象数组格式
        let silderImgsArr = this.formData.silderImgs.map((url, index) => ({
          attId: Date.now() + index,
          name: url.split('/').pop() || `image_${index + 1}.jpg`,
          attDir: "",
          sattDir: url,
          attSize: "0",
          attType: (url.split('.').pop() || 'jpg').toLowerCase(),
          pid: 0,
          imageType: 1,
          createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
          updateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
          localImg: "",
          isSelect: true,
          num: index + 1
        }));
        const data = {
          ...this.formData,
          startTime: this.timeToHour(this.formData.startTime),
          endTime: this.timeToHour(this.formData.endTime),
          status: this.formData.status,
          silderImgs: silderImgsArr.length > 0 ? JSON.stringify(silderImgsArr) : null,
        };

        if (data.id) {
          await StoreSeckillMangerApi.updateStoreSeckillManger(data);
          this.$message.success("修改成功");
        } else {
          await StoreSeckillMangerApi.createStoreSeckillManger(data);
          this.$message.success("新增成功");
        }
        
        this.dialogVisible = false;
        // 触发父组件的刷新方法
        this.$emit('success');
        // 重置表单
        this.reset();
      } catch (error) {
        this.$message.error(error.message || "操作失败，请重试");
      } finally {
        this.formLoading = false;
      }
    },
    reset() {
      this.formData = {
        id: null,
        name: null,
        startTime: null,
        endTime: null,
        silderImgs: [],
        status: "1", // 默认开启
      };
      this.tempStartTime = null;
      this.tempEndTime = null;
      if (this.$refs.formRef) this.$refs.formRef.resetFields();
    },
    // 解析图片数据
    parseImageData(imageData) {
      if (!imageData) return [];
      try {
        if (typeof imageData === 'string') {
          const parsed = JSON.parse(imageData);
          if (Array.isArray(parsed)) {
            return parsed.map(item => item.sattDir || '').filter(Boolean);
          }
        }
        if (Array.isArray(imageData)) {
          return imageData.map(item => item.sattDir || '').filter(Boolean);
        }
        return [];
      } catch (error) {
        console.error('解析图片数据失败:', error);
        return [];
      }
    },
    // 处理拖拽结束
    handleDragEnd() {
      // 拖拽结束后，更新图片顺序
      this.$forceUpdate();
    },
    // 删除图片
    removeImage(index) {
      this.$confirm('确认删除该图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.silderImgs.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {});
    },
  },
};
</script>

<style scoped>
.image-upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 10px;
}

.image-preview-container {
  margin-top: 10px;
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 10px;
}

.image-list {
  display: flex;
  gap: 10px;
  min-height: 80px;
  padding: 5px 0;
  scrollbar-width: thin;
  scrollbar-color: #909399 #f4f4f5;
}

.image-list::-webkit-scrollbar {
  height: 6px;
}

.image-list::-webkit-scrollbar-track {
  background: #f4f4f5;
  border-radius: 3px;
}

.image-list::-webkit-scrollbar-thumb {
  background: #909399;
  border-radius: 3px;
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
  flex-shrink: 0;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.drag-handle {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 16px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  z-index: 1;
  font-size: 12px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 16px;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-actions .el-button {
  color: white;
  padding: 0;
  font-size: 12px;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 16px;
}

/* 添加上传组件的滚动样式 */
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 80px;
}

:deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 10px;
  margin: 0;
  width: 100%;
  scrollbar-width: thin;
  scrollbar-color: #909399 #f4f4f5;
}

:deep(.el-upload-list--picture-card::-webkit-scrollbar) {
  height: 6px;
}

:deep(.el-upload-list--picture-card::-webkit-scrollbar-track) {
  background: #f4f4f5;
  border-radius: 3px;
}

:deep(.el-upload-list--picture-card::-webkit-scrollbar-thumb) {
  background: #909399;
  border-radius: 3px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  margin-bottom: 0;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>